package c_admin

import (
	"fmt"
	"gintest/models"
	"gintest/until"
	"github.com/gin-gonic/gin"
	"strconv"
	"strings"
	"time"
)

func Store_list(c *gin.Context){
	page,_:=strconv.ParseUint(c.DefaultPostForm("page","1"),10,64)
	pagesize,_:=strconv.ParseUint(c.DefaultPostForm("limit","15"),10,64)
	keyword:=c.DefaultPostForm("keyword","")
	list,total:=models.GetStoreList(page,pagesize,keyword,0)
	until.Success(c,map[string]interface{}{"data":list,"total":total})
}
func Store_doadd(c *gin.Context){
	var form models.Store

	if err:=c.ShouldBind(&form);err!=nil{
		until.Fail(c,1,err.Error())
		return
	}
	if len(form.Title)==0 {
		until.Fail(c,1,"title field cannot be empty")
		return
	}
	if form.ClassId<=0 {
		until.Fail(c,1,"classid field cannot be empty")
		return
	}
	if err:=models.AddStore(&form);err!=nil{
		until.Fail(c,1,err.Error())
		return
	}
	until.Success(c, nil)

}
func Store_detail(c *gin.Context){
	id:=c.DefaultPostForm("id","")
	if len(id)==0{
		until.Fail(c,1,"id field cannot be empty")
		return
	}
	aid,_:=strconv.Atoi(id)
	data:=models.GetStoreById(aid)
	until.Success(c,data)

}
func Store_doedit(c *gin.Context){
	/*格式化参数*/
	c.PostForm("") //相当于parseForm+ParseMultipartForm
	//c.Request.ParseForm()
	//c.Request.ParseMultipartForm(32 << 20)
	form:=make(map[string]interface{})
	var id int
	for k, v := range c.Request.PostForm {
		val:=strings.Trim(fmt.Sprint(v), "[]")

		if k=="id"{
			id,_=strconv.Atoi(val)
		} else if k=="status" ||k=="class_id" {
			form[k],_=strconv.Atoi(val)
		}else if k=="create_at" || k=="update_at" || k=="delete_at"{
			form[k],_= time.ParseInLocation("2006-01-02 15:04:05", val, time.Local)
		}else{
			form[k] = val
		}
	}
	/*参数验证*/
	if id <= 0 {
		until.Fail(c, 1, "id field cannot be empty")
		return
	}
	if v, ok := form["class_id"];ok && v.(int)<=0{
		until.Fail(c, 1, "classid field cannot be empty")
		return
	}
	/*更新数据库*/
	if err:=models.EditStoreById(id,form);err != nil{
		until.Fail(c,1,err.Error())
		return
	}

	until.Success(c, nil)


}
func Store_del(c *gin.Context){
	idsstr:=c.DefaultPostForm("id","")
	idsstr_arr := strings.Split(idsstr, ",")
	var ids []int
	for i:=0;i<len(idsstr_arr);i++{
		intt,_:=strconv.Atoi(idsstr_arr[i])
		ids=append(ids,intt)
	}
	if err:=models.DelStoreByIds(ids);err!=nil{
		until.Fail(c,1,err.Error())
		return
	}
	until.Success(c,nil)
}
